package com.sport.controller;

import com.google.gson.Gson;
import com.sport.constant.WsResultConstant;
import com.sport.pojo.dto.Referee;
import com.sport.pojo.vo.WsResult;
import com.sport.result.Result;
import com.sport.service.JudgeService;
import com.sport.service.RoomService;
import com.sport.service.RoomService2;
import com.sport.websocket.RoomWs2;
import com.sport.websocket.WsEnd;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user/judge")
@Api(tags = "裁判相关接口")
public class JudgeController {
    @Autowired
    private JudgeService judgeService;
    @Autowired
    private RoomWs2 roomWs;

    @Autowired
    private WsEnd wsEnd;


    @ApiOperation("裁判加入房间")
    @PutMapping("/addJudge")
    public Result addJudge(@RequestBody Referee referee) {
        int info = judgeService.addJudge(referee);
        if (info == 1) {
            roomWs.broadcast(referee.getRoomId(), new Gson().toJson(new WsResult(WsResultConstant.ADD_JUDGE, "加入裁判", referee.getAvatar())));
            return Result.success();
        } else if (info == 2) {
            roomWs.broadcast(referee.getRoomId(), new Gson().toJson(new WsResult(12, "房间人满", referee.getAvatar())));
            return Result.success("房间人满", 501);
        } else {
            return Result.error("加入失败");
        }
    }

    @ApiOperation("裁判开始房间")
    @GetMapping("/start")
    public Result start(String roomId) {
        int info = judgeService.start(roomId);
        if (info == 1) {
            roomWs.broadcast(roomId, new Gson().toJson(new WsResult(WsResultConstant.START_GAME, "开始游戏", "")));
            return Result.success();
        } else if (info == 2) {
            return Result.success("人没满", 502);
        } else {
            return Result.error("开始失败");
        }
    }
    @ApiOperation("裁判结束房间")
    @GetMapping("/end")
    public  Result endGame(String roomId,String redScore,String blueScore){
        int info = judgeService.endGame(roomId,redScore,blueScore);
        if(info==1){
            wsEnd.broadcast(roomId,new Gson().toJson(new WsResult(WsResultConstant.END_GAME, "结束游戏", "")));
            //广播结束消息
            return Result.success();
        }else{
            return Result.error("结束失败");
        }
    }

}
